# -*- coding: utf_8 -*-
# @Create   : 2021/9/1 11:10
# @Author   : yh
# @Remark   : 巡检任务view层

from mxsoftpy import View


from server.common.VideoManage.VideoQuality.inspection_task import InspectionSourceServer, InspectionTaskServer
from utils.public.params_method import check_params, pro_decode
from view.common.VideoManage.VideoQuality.inspection_plan import _check_items


def _check_video(video):
    """
    params: video video_code
    """
    # 校验video是否可用
    # noinspection PyBroadException
    from db.common.VideoManage.VideoQuality.video import VideoDB

    res = VideoDB().simple_list()
    video_list = list(res.keys())
    if video not in video_list:
        return False
    else:
        return True


class InspectionTempTaskAdd(View):

    def post(self):
        """
        添加临时巡检任务
        """
        check_params(self.request.POST, ['videos', 'TestItems', 'name', 'principal'])
        self.request.POST['TestItems'] = _check_items(self.request.POST['TestItems'])
        param = pro_decode(**self.request.POST)  # 解码

        for i in param['videos'].split(';'):
            if not i.isdigit():
                return '错误的videos数据，有数据无法转为int类型'
            if not _check_video(i):
                return f'错误的videos数据，video_code:{i}已停用或不存在'

        if param['TestItems'] is False:
            return 'test_items属性错误，无法序列化或不是List'
        else:
            return '添加巡检任务成功', {'task_code': InspectionTaskServer().create(**param)}


class InspectionTaskSelect(View):

    def post(self):
        """
        查询巡检任务
        """
        check_params(self.request.POST, ['begin_time', 'end_time', 'name', 'state', 'task_state', 'plan_code'])
        param = pro_decode(**self.request.POST)  # 解码

        return '查询巡检任务成功', InspectionTaskServer().select(**param)


class InspectionTaskDelete(View):

    def post(self):
        """
        删除巡检任务
        """
        check_params(self.request.POST, ['task_code'])

        return '删除巡检任务成功', InspectionTaskServer().delete(**self.request.POST)


class InspectionSourceSelect(View):

    def post(self):
        """
        任务来源联想查询
        """
        check_params(self.request.POST, ['name'])

        return '查询任务来源成功', InspectionSourceServer().select(**self.request.POST)
